package com.itheima.service.impl;
import	java.awt.Desktop.Action;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.ValidateCodeService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 代码使我快乐 Administrator on 2019/12/10.
 */
@Service(interfaceClass = ValidateCodeService.class)
@Transactional
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private JedisPool jedisPool;


    /**
     * 发送验证码
     * @param telephone 要发送的手机号
     * @param sendType 验证码的类型
     * @return
     */
    private Result sendSMS(String telephone, String sendType) {
        boolean flag = true;
        String message = MessageConstant.SEND_VALIDATECODE_SUCCESS;

        Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone ,validateCode.toString());
        } catch (ClientException e) {
            e.printStackTrace();

            flag = false;
            message = MessageConstant.SEND_VALIDATECODE_FAIL;
        }

        if (flag) {
            Jedis jedis = jedisPool.getResource();
            jedis.setex(telephone+sendType,300 ,validateCode.toString() );
            jedis.close();
        }

        return new Result(flag,message);
    }

    @Override
    public Result send4Order(String telephone, String sendType) {
        Result result = sendSMS(telephone, RedisMessageConstant.SENDTYPE_ORDER);
        return result;
    }

    @Override
    public Result send4Login(String telephone, String sendType) {
        Result result = sendSMS(telephone, RedisMessageConstant.SENDTYPE_LOGIN );
        return result;
    }

    /**
     * 进行验证码是否正确的检验
     * @param telephone  手机号
     * @param code 用户输入的验证码
     * @param validateCodeType 验证码的类型
     * @return
     */
    @Override
    public boolean validate(String telephone, String code, String validateCodeType) {

        Jedis jedis = jedisPool.getResource();
        String s = jedis.get(telephone + validateCodeType);
        jedis.close();
        if(s != null && s.equals(code)){
            return true;
        }
        return false;
    }
}
